<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6" :xs="24">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>个人信息</span>
          </div>
          <div>
            <div class="text-center">
              <userAvatar />
            </div>
            <ul class="list-group list-group-striped">
              <li class="list-group-item">
                <svg-icon icon-class="user" />用户名称
                <div class="pull-right">{{ user.userName }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="phone" />手机号码
                <div class="pull-right">{{ user.phonenumber }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="email" />用户邮箱
                <div class="pull-right">{{ user.email }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="tree" />所属部门
                <div class="pull-right" v-if="user.dept">{{ user.dept.deptName }} / {{ postGroup }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="peoples" />所属角色
                <div class="pull-right">{{ roleGroup }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="date" />创建日期
                <div class="pull-right">{{ user.createTime }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="qrcode" />联系二维码
                <div class="pull-right">
                  <el-button 
                    v-if="user.userCode" 
                    type="text" 
                    size="mini" 
                    @click="viewQrCode"
                  >查看</el-button>
                  <el-button 
                    type="text" 
                    size="mini" 
                    @click="editQrCode"
                  >{{ user.userCode ? '修改' : '添加' }}</el-button>
                </div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="fire" />阅后即焚
                <div class="pull-right">
                  <el-button 
                    type="text" 
                    size="mini" 
                    @click="createBurnAfterReading"
                  >创建</el-button>
                  <el-button 
                    type="text" 
                    size="mini" 
                    @click="viewBurnAfterReadingLinks"
                  >查看链接</el-button>
                </div>
              </li>
            </ul>
          </div>
        </el-card>
      </el-col>
      <el-col :span="18" :xs="24">
        <el-card>
          <div slot="header" class="clearfix">
            <span>个人中心</span>
          </div>
          <el-tabs v-model="selectedTab">
            <el-tab-pane label="我的任务单" name="myTasks">
              <my-tasks :userId="user.userId"/>
            </el-tab-pane>
            <el-tab-pane label="订单预警" name="orderAlerts">
              <order-alerts />
            </el-tab-pane>
            <el-tab-pane label="退款管理" name="cancellationMgmt">
              <cancellation-mgmt />
            </el-tab-pane>
            <el-tab-pane label="信用等级" name="creditLevel">
              <credit-level :user="user"/>
            </el-tab-pane>
            <el-tab-pane label="基本资料" name="userinfo">
              <user-info :user="user" />
            </el-tab-pane>
            <el-tab-pane label="修改密码" name="resetPwd">
              <reset-pwd />
            </el-tab-pane>
            <el-tab-pane v-if="!isAdminOrExternalTech" label="报销申请" name="reimbursementApply">
              <reimbursement-apply :userId="user.userId" />
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>

    <!-- 二维码查看对话框 -->
    <el-dialog title="联系二维码" :visible.sync="qrCodeViewOpen" width="400px" append-to-body center>
      <div class="qr-code-panel">
        <div v-if="user.userCode" class="qr-code-section">
          <img :src="user.userCode" alt="联系二维码" class="qr-code-image">
          <p class="qr-tip">扫描二维码联系我</p>
        </div>
        <el-empty v-else description="暂无二维码"></el-empty>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="qrCodeViewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 二维码编辑对话框 -->
    <el-dialog :title="user.userCode ? '修改二维码' : '添加二维码'" :visible.sync="qrCodeEditOpen" width="500px" append-to-body>
      <el-form ref="qrCodeForm" :model="qrCodeForm" :rules="qrCodeRules" label-width="80px">
        <el-form-item label="二维码" prop="qrCodeFile">
          <el-upload
            ref="upload"
            :limit="1"
            accept="image/*"
            :headers="uploadHeaders"
            :action="uploadUrl"
            :before-upload="beforeQrCodeUpload"
            :on-success="handleQrCodeSuccess"
            :on-error="handleQrCodeError"
            :auto-upload="true"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过5MB</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="qrCodeEditOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitQrCode">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 阅后即焚创建对话框 -->
    <el-dialog title="创建阅后即焚" :visible.sync="burnAfterReadingCreateOpen" width="500px" append-to-body>
      <el-form ref="burnAfterReadingForm" :model="burnAfterReadingForm" :rules="burnAfterReadingRules" label-width="80px">
        <el-form-item label="图片" prop="imageFile">
          <el-upload
            ref="burnUpload"
            :limit="1"
            accept="image/*"
            :headers="uploadHeaders"
            :action="burnUploadUrl"
            :before-upload="beforeBurnUpload"
            :on-success="handleBurnSuccess"
            :on-error="handleBurnError"
            :auto-upload="true"
            name="file"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将图片拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过10MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="burnAfterReadingForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息（可选）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="burnAfterReadingCreateOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitBurnAfterReading" :loading="burnSubmitting">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 阅后即焚链接列表对话框 -->
    <el-dialog title="我的阅后即焚链接" :visible.sync="burnAfterReadingListOpen" width="800px" append-to-body>
      <el-table :data="burnAfterReadingLinks" v-loading="burnLinksLoading">
        <el-table-column prop="imageId" label="链接ID" width="200">
          <template slot-scope="scope">
            <el-button type="text" @click="copyToClipboard(scope.row.accessUrl)">
              {{ scope.row.imageId }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
              {{ scope.row.status === 0 ? '有效' : '已失效' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button 
              type="text" 
              size="mini" 
              @click="copyToClipboard(scope.row.accessUrl)"
              :disabled="scope.row.status !== 0"
            >
              复制链接
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="burnAfterReadingListOpen = false">关 闭</el-button>
        <el-button type="primary" @click="createLinkFromSaved" :loading="burnLinksLoading">创建链接</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import userAvatar from "./userAvatar"
import userInfo from "./userInfo"
import resetPwd from "./resetPwd"
import myTasks from "./myTasks"
import orderAlerts from "./orderAlerts"
import reimbursementApply from "./reimbursementApply"
import cancellationMgmt from "./cancellationMgmt"
import creditLevel from "./creditLevel"
import { getUserProfile } from "@/api/system/user"
import { getToken } from "@/utils/auth"
import { uploadQrCode, saveUserCode, uploadBurnAfterReading, createBurnAfterReadingLink, getBurnAfterReadingLinks, saveReadingLink } from "@/api/system/user"

export default {
  name: "Profile",
  components: { userAvatar, userInfo, resetPwd, myTasks, orderAlerts, cancellationMgmt, creditLevel,reimbursementApply },
  data() {
    return {
      user: {},
      roleGroup: "",
      postGroup: {},
      selectedTab: "myTasks",
      // 二维码相关
      qrCodeViewOpen: false,
      qrCodeEditOpen: false,
      qrCodeForm: {
        qrCodeFile: null
      },
      qrCodeRules: {},
      uploadUrl: process.env.VUE_APP_BASE_API + "/system/user/uploadQrCode",
      uploadHeaders: { Authorization: "Bearer " + getToken() },
      // 阅后即焚相关
      burnAfterReadingCreateOpen: false,
      burnAfterReadingListOpen: false,
      burnAfterReadingForm: {
        imageFile: null,
        remark: ""
      },
      burnAfterReadingRules: {},
      burnUploadUrl: process.env.VUE_APP_BASE_API + "/system/burnAfterReading/upload",
      burnSubmitting: false,
      burnAfterReadingLinks: [],
      burnLinksLoading: false
    }
  },
  created() {
    const activeTab = this.$route.params && this.$route.params.activeTab
    if (activeTab) {
      this.selectedTab = activeTab
    }
    this.getUser()
  },
  computed: {
      isAdminOrExternalTech() {
         const roles = this.roleGroup ? this.roleGroup.split(',') : [];
        return roles.includes("超级管理员") || roles.includes("外包技术");
      },
  },
  methods: {
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data
        this.roleGroup = response.roleGroup
        this.postGroup = response.postGroup
      })
    },
    
    // 查看二维码
    viewQrCode() {
      this.qrCodeViewOpen = true;
    },
    
    // 编辑二维码
    editQrCode() {
      // 重置表单状态
      this.qrCodeForm.qrCodeFile = null;
      this.qrCodeEditOpen = true;
    },
    
    // 上传前检查
    beforeQrCodeUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt5M = file.size / 1024 / 1024 < 5; // 改为5MB限制
      
      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }
      if (!isLt5M) {
        this.$message.error('图片大小不能超过 5MB!');
        return false;
      }
      return true;
    },
    
    // 上传成功
    handleQrCodeSuccess(response, file) {
      if (response.code === 200) {
        // 根据接口返回的数据结构设置
        // AjaxResult.success("消息", data) 的第二个参数是数据
        this.qrCodeForm.qrCodeFile = response.data;
        
        // 强制更新Vue响应式数据
        this.$forceUpdate();
        
        this.$message.success('二维码上传成功');
        // 上传成功后不自动保存，等待用户点击确定
      } else {
        this.$message.error(response.msg || '二维码上传失败');
      }
    },
    
    // 上传失败
    handleQrCodeError(err, file, fileList) {
      this.$message.error('二维码上传失败');
    },
    
    // 提交二维码
    submitQrCode() {
      if (!this.qrCodeForm.qrCodeFile) {
        this.$message.error('请先上传二维码');
        return;
      }
      
      // 调用saveUserCode接口保存二维码
      const userData = {
        userId: this.user.userId,
        userCode: this.qrCodeForm.qrCodeFile
      };
      
      saveUserCode(userData).then(response => {
        if (response.code === 200) {
          this.$message.success('二维码保存成功');
          this.qrCodeEditOpen = false;
          this.getUser(); // 刷新用户信息
        } else {
          this.$message.error(response.msg || '二维码保存失败');
        }
      }).catch(error => {
        this.$message.error('二维码保存失败');
      });
    },

    // ========== 阅后即焚相关方法 ==========
    
    // 创建阅后即焚
    createBurnAfterReading() {
      this.burnAfterReadingForm = {
        imageFile: null,
        remark: ""
      };
      this.burnAfterReadingCreateOpen = true;
    },
    
    // 查看阅后即焚链接列表
    viewBurnAfterReadingLinks() {
      this.burnAfterReadingListOpen = true;
      this.loadBurnAfterReadingLinks();
    },
    
    // 加载阅后即焚链接列表
    loadBurnAfterReadingLinks() {
      this.burnLinksLoading = true;
      getBurnAfterReadingLinks().then(response => {
        if (response.code === 200) {
          this.burnAfterReadingLinks = response.data.map(item => ({
            ...item,
            accessUrl: window.location.origin + "/burn-after-reading/" + item.imageId
          }));
        } else {
          this.$message.error(response.msg || '获取链接列表失败');
        }
      }).catch(error => {
        this.$message.error('获取链接列表失败');
      }).finally(() => {
        this.burnLinksLoading = false;
      });
    },
    
    // 阅后即焚图片上传前检查
    beforeBurnUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt10M = file.size / 1024 / 1024 < 10; // 10MB限制
      
      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }
      if (!isLt10M) {
        this.$message.error('图片大小不能超过 10MB!');
        return false;
      }
      return true;
    },
    
    // 阅后即焚图片上传成功
    handleBurnSuccess(response, file) {
      // 调试输出后端返回
      try { console.log('burn upload response:', response); } catch (e) {}
      if (response.code === 200) {
        const data = response.data;
        const pickFirstTruthy = (...vals) => vals.find(v => typeof v === 'string' && v.trim().length > 0) || '';
        const candidate = pickFirstTruthy(
          data && typeof data === 'object' && data.url,
          data && typeof data === 'object' && data.imageUrl,
          typeof data === 'string' && data,
          response.url,
          response.msg,
          response.message
        );
        // 放宽校验：接受任意非空字符串
        this.burnAfterReadingForm.imageFile = candidate;
        if (this.burnAfterReadingForm.imageFile) {
          this.$message.success('图片上传成功');
        } else {
          this.$message.error('上传成功但未获取到图片URL');
        }
      } else {
        this.$message.error(response.msg || '图片上传失败');
      }
    },
    
    // 阅后即焚图片上传失败
    handleBurnError(err, file, fileList) {
      this.$message.error('图片上传失败');
    },
    
    // 提交阅后即焚
    submitBurnAfterReading() {
      if (!this.burnAfterReadingForm.imageFile) {
        this.$message.error('请先上传图片');
        return;
      }
      this.burnSubmitting = true;

      // 先保存图片到用户 readingLink
      saveReadingLink({ imageUrl: this.burnAfterReadingForm.imageFile })
        .then(res => {
          if (res && res.code === 200) {
            this.$message.success('图片已保存');
            this.burnAfterReadingCreateOpen = false;
            // 可选：打开列表页，便于用户继续创建链接
            this.viewBurnAfterReadingLinks();
          } else {
            this.$message.error((res && res.msg) || '图片保存失败');
          }
        })
        .catch(() => {
          this.$message.error('图片保存失败');
        })
        .finally(() => {
          this.burnSubmitting = false;
        });
    },

    // 从已保存的图片创建阅后即焚链接
    createLinkFromSaved() {
      if (!this.burnAfterReadingForm.imageFile) {
        this.$message.error('请先在“创建”里上传并保存图片');
        return;
      }
      const params = {
        userId: this.user.userId,
        imageUrl: this.burnAfterReadingForm.imageFile,
        remark: this.burnAfterReadingForm.remark
      };
      this.burnLinksLoading = true;
      createBurnAfterReadingLink(params)
        .then(response => {
          if (response.code === 200) {
            const result = response.data;
            const fullUrl = window.location.origin + result.accessUrl;
            this.copyToClipboard(fullUrl);
            this.$message.success('阅后即焚链接创建成功，已复制到剪贴板');
            this.loadBurnAfterReadingLinks();
          } else {
            this.$message.error(response.msg || '创建阅后即焚链接失败');
          }
        })
        .catch(() => {
          this.$message.error('创建阅后即焚链接失败');
        })
        .finally(() => {
          this.burnLinksLoading = false;
        });
    },
    
    // 复制到剪贴板
    copyToClipboard(text) {
      if (navigator.clipboard) {
        navigator.clipboard.writeText(text).then(() => {
          this.$message.success('链接已复制到剪贴板');
        }).catch(() => {
          this.fallbackCopyToClipboard(text);
        });
      } else {
        this.fallbackCopyToClipboard(text);
      }
    },
    
    // 降级复制方法
    fallbackCopyToClipboard(text) {
      const textArea = document.createElement('textarea');
      textArea.value = text;
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      try {
        document.execCommand('copy');
        this.$message.success('链接已复制到剪贴板');
      } catch (err) {
        this.$message.error('复制失败，请手动复制');
      }
      document.body.removeChild(textArea);
    }
  }
}
</script>

<style scoped>
.qr-code-panel {
  text-align: center;
  padding: 20px 0;
}

.qr-code-section {
  margin-bottom: 20px;
}

.qr-code-image {
  width: 200px;
  height: 200px;
  object-fit: cover;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.qr-tip {
  margin-top: 15px;
  color: #606266;
  font-size: 14px;
}

.el-upload__tip {
  color: #909399;
  font-size: 12px;
  margin-top: 10px;
}
</style>